package com.htjc.integral.account.config;


import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "jfLog")
@Configuration
@MapperScan(basePackages = "com.htjc.integral.account.mapper.newdb", sqlSessionTemplateRef  = "newSqlSessionTemplate")
public class NewDataSourceConfiguration {

	@Value("${mybatis.type-aliases-package}")
	private String typeAliasesPackage;
	
	@Value("${mybatis.mapper-locations}")
	private String mapperLocations;
	
    @Bean(name = "newDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.new")
    @Primary
    public DataSource DataSource() {
    	log.debug("创建数据库源=============new");
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "newSqlSessionFactory")
    @Primary
    public SqlSessionFactory SqlSessionFactory(@Qualifier("newDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage(typeAliasesPackage);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        return bean.getObject();
    }

    @Bean(name = "newTransactionManager")
    @Primary
    public DataSourceTransactionManager TransactionManager(@Qualifier("newDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "newSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate SqlSessionTemplate(@Qualifier("newSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

	
	
}
